<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">
<link href="/js/advanced-datatable/css/demo_page.css" rel="stylesheet" />
<link href="/js/advanced-datatable/css/demo_table.css" rel="stylesheet" />
<link rel="stylesheet" href="/js/data-tables/DT_bootstrap.css" />

<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">

<body class="panel" style="padding: 0;">
	<div class="row">
		<div class="col-sm-12">
			<div class="panel-body">
				<header class="panel-heading" style="height: 50;">
					<div class="col-lg-10">API访问账户列表&nbsp;&nbsp;(以下用户凭借token可以访问被授权的API)</div>
					<div class="col-lg-2" align="right"><button data-toggle="modal" href="#myModal" class="btn btn-success  btn-sm" onclick="clearAddFrom()">新增api user</button>

				</header>
				<div class="adv-table ">
					<table class="  table " id="listTable">
						<thead>
							<tr>

								<th width="20%">用户名</th>
								<th width="30%">token</th>
								<th width="30%"> 描述</th>
								<th width="20%"></th>
							</tr>
						</thead>

						<tbody id="maintablebody">
						</tbody>
					</table>
				</div>
				<footer>
					<label>
						<select class="form-control" id="stepInput" onchange="currentPage = 1;changeStep(false)" size="1" name="hidden-table-info_length" aria-controls="hidden-table-info">
						<option value="10" selected="selected">10</option>
						<option value="25">25</option>
						<option value="50">50</option>
						<option value="100">100</option>
					</select> records per page</label>

					<div id="pageLabelDiv" class="dataTables_paginate paging_bootstrap pagination">
						<ul>
						</ul>
					</div>
				</footer>
				</div>

			</div>
			<!--	//-----------弹出创建api user 的窗口------start------------>
			<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
							<h4 class="modal-title">添加API USER</h4>
						</div>
						<input type="text" id="token" hidden="hidden" />
						<div class="modal-body row">
							<div class="col-lg-5">
								<div class="form-group">
									<label>用户名</label>
									<input type="text" class="form-control" id="user_name" />
								</div>
							</div>
							<div class="col-lg-5">
								<div class="form-group">
									<label>密码</label>
									<input type="text" class="form-control" id="password" />
								</div>
							</div>
							<div class="col-lg-2">
								<div class="form-group">
									<label>启用</label> <br />
									<input type="checkbox" id="apiEnable" name="apiEnable" checked />
								</div>

							</div>
						</div>
						<div class="modal-body row">

							<div class="col-lg-10">
								<div class="form-group">
									<label>描述</label>
									<input type="text" class="form-control" id="description" />
								</div>
							</div>
							<div class="col-lg-2">
								<div class="form-group">
									<br />
									<button class="btn btn-success  btn-sm" onclick="saveNewitem()">保存</button>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!--   //-----------弹出创建app的窗口------end----------      -->

			<!--	//-----------弹出创建setUserAPIModal 的窗口------start------------>
			<div class="modal fade" id="setUserAPIModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
							<h4 class="modal-title">设置用户能使用的API</h4>
						</div>
						<div class="modal-body row">
							<div class="col-lg-12">
							<div class="form-group">
							<table class="display table " id="allApiUserSelector" width="100%">

								<tbody id="apitablebody">
								</tbody>
								</div>
							</table>
						</div></div>
						<div class="modal-body row">
							<div class="col-lg-5">

							</div>
							<div class="col-lg-2">
								<div class="form-group">
									<br />
									<button class="btn btn-success  btn-sm" onclick="saveApiUserUrl()">保存</button>
								</div>
							</div>
							<div class="col-lg-5">

							</div>
						</div>
					</div>
				</div>
			</div>
			<!--   //-----------弹出创建setUserAPIModal的窗口------end----------      -->

			<!-- Placed js at the end of the document so the pages load faster -->
			<script src="/js/jquery-1.10.2.min.js"></script>
			<script src="/js/jquery-ui-1.9.2.custom.min.js"></script>
			<script src="/js/jquery-migrate-1.2.1.min.js"></script>
			<script src="/js/bootstrap.min.js"></script>
			<script src="/js/modernizr.min.js"></script>
			<script src="/js/jquery.nicescroll.js"></script>
			<!--common scripts for all pages-->
			<script src="/js/scripts.js"></script>
			<script src="/js/html5shiv.js"></script>
			<script src="/js/respond.min.js"></script>
			<script>
				var totalCount = 0
				var currentPage = 1
				var step = 10
				var currentId = 0
				var tablebody
				var apiUserList
				var adddata
				var host
				var userWithPirvilege
				var currentAppId = -1
					//从API获取数据列表
				function getList(page, tempstep) {
					currentPage = page;
					step = tempstep
					$.get(host + "/list_api_user/" + currentPage + "/step/" + step, null, listToSuccess, "json");
				}
				//页面载入后先获取默认条数的数据
				window.onload = function() {
					host = "http://" + window.location.host
					getList(currentPage, step);
				};
				//从数据库中获取列表成功
				function listToSuccess(response, status, xhr) {

					if(status == "success" && response.reusltCode == "200") {
						apiUserList = response.reusltDetail.apiuserlist;
						userWithPirvilege = response.reusltTitle;
						totalCount = response.totalCount;
						clearDataTable();
						changeStep(true);
						fillTable();
						parent.setMainContentHeight(apiUserList.length,50);  
						getApiUserList();
						
						
					} else {
						alert(response);
					}
				}
				 function onBodyResize() { 
 
		}
				//采用本地数组中的数据填充表格
				function fillTable() {
					adddata = "";
					$.each(apiUserList, function(index, item) {
						adddata += ("<tr ");

						var start_s = "<u><s>";
						var end_s = "</s></u>";
						if(item.enable == 1) {
							start_s = "";
							end_s = "";
						}
						adddata += ("  name=" + index + ">");
						adddata += ("<td  width='20%'>" + start_s + item.user_name + end_s + "</td>");
						adddata += ("<td  width='30%'>" + start_s + item.token + end_s + "</td>");
						adddata += ("<td width='30%'>" + start_s + item.description + end_s + "</td>");
						if(userWithPirvilege.is_manager == true) {
							adddata += ("<td align='right' width='20%'> <a data-toggle='modal' href='#myModal'  class='tn btn-success btn-sm' onclick='editAppItem(" + index + ")' >编辑</a><a data-toggle='modal' href='#setUserAPIModal'  class='tn btn-warning btn-sm' onclick='setUserAPI(" + index + ")' >赋权</a></td>");
						}
						adddata += "</tr>";
					});
					tablebody.append(adddata);
				}
				//点击编辑按钮的时候
				function editAppItem(i) {
					currentTabIndex = i;
					currentAppId = apiUserList[i].id;
					document.getElementById("token").value = apiUserList[i].token;
					document.getElementById("description").value = apiUserList[i].description;
					document.getElementById("user_name").value = apiUserList[i].user_name;
					document.getElementById("password").value = apiUserList[i].password;
					if(apiUserList[i].enable == 1) {
						document.getElementById("apiEnable").checked = true;
					} else {
						document.getElementById("apiEnable").checked = false;
					}
				} //点击编辑按钮的时候
				function saveNewitem() {
					var currentdata = new Object();
					currentdata.id = currentAppId;
					currentdata.token = document.getElementById("token").value;
					currentdata.description = document.getElementById("description").value;
					currentdata.user_name = document.getElementById("user_name").value;
					currentdata.password = document.getElementById("password").value;
					if(document.getElementById("apiEnable").checked == true) {
						currentdata.enable = 1;
					} else {
						currentdata.enable = 0;
					}
					currentdata.page = currentPage;
					currentdata.step = step;
					$.ajaxSetup({
						contentType: 'application/json'
					});
					$.post(host + "/add_api_user", JSON.stringify(currentdata), saveSuccess, "json");
				}
				//保存成功
				function saveSuccess(response, status, xhr) {
					if(status == "success" && response.reusltCode == "200") {
						console.log(response)
						listToSuccess(response, status, xhr);
						currentAppId = 0;
						$('#myModal').modal('hide');
					} else {
						alert(response);
					}

				}
				//清空数据表格
				function clearDataTable() {
					tablebody = $("#maintablebody");
					tablebody.empty();
					apitablebody = document.getElementById("apitablebody");
				}

				//每页的条数发生改变时  重新计算分页条数
				function changeStep(onlyChangeStep) {
					var pagelabelDiv = $("#pageLabelDiv ul");
					pagelabelDiv.empty();
					var stepinput = document.getElementById("stepInput")
					step = parseInt(stepinput.options[stepinput.selectedIndex].value);
					var pageNum = Math.ceil(totalCount / step);
					if(currentPage <= 1) {
						pagelabelDiv.append('<li class="prev disabled"><a href="#">← Previous</a></li>')
					} else {
						pagelabelDiv.append('<li class="prev" onclick="getList(' + (currentPage - 1) + ',' + step + ')" ><a href="#">← Previous</a></li>')
					}
					if(pageNum > 6) {
				for(var i = 1; i <= pageNum; i++) {
					if((i) == currentPage) {
						pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
					} else if((i <= 2)) {
						pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
					} else if((i >= currentPage - 1 && (i <=currentPage + 1)) || (i > pageNum - 2)) {
						pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
					}
				}

			} else {
					for(var i = 1; i <= pageNum; i++) {
						if((i) == currentPage) {
							pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
						} else {
							pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
						}
					}
					}
					if(currentPage >= pageNum) {
						pagelabelDiv.append('<li class="next disabled"><a href="#">Next → </a></li>')
					} else {
						pagelabelDiv.append('<li class="next" onclick="getList(' + (currentPage + 1) + ',' + step + ')" ><a href="#">Next → </a></li>')
					}
					if(onlyChangeStep == false) {
						getList(currentPage, step);
					}
				}

				function getApiUserList() {
					$.get(host + "/list_api_url/1/step/10000", null, listApiuserToSuccess, "json");
				}
				var apiurlList
				var apitablebody
				var apiUserUrlList
				var currentApiUserId

				function listApiuserToSuccess(response, status, xhr) {
					if(status == "success" && response.reusltCode == "200") {
						apiurlList = response.reusltDetail.apiUrllist;
						apiUserUrlList = response.reusltDetail.apiuserurl;
						//	clearApiuserTable();
					} else {
						alert(response);
					}
				}

				//设置可以使用这个API的账户
				function setUserAPI(i) {
					currentTabIndex = i;
					currentApiUserId = apiUserList[i].token;
					fillApiUserSelecter();
				}
				//采用本地数组中的数据填充表格
				function fillApiUserSelecter() {
					//	console.log("1-----------", apiurlList.length)
					var innerhtmltext = ""
					var userListOfthisApiUrl = new Array();
					for(key in apiUserUrlList) {
						for(var i = 0; i < apiUserUrlList[key].length; i++) {
							if(apiUserUrlList[key][i] == currentApiUserId) {

								userListOfthisApiUrl = userListOfthisApiUrl.concat(key)
							}
						}
					}

					for(var j = 0; j < apiurlList.length; j++) {
						innerhtmltext += ("<tr><td><input type='checkbox' ")
						for(var m = 0; m < userListOfthisApiUrl.length; m++) {
							if(userListOfthisApiUrl[m] == apiurlList[j].url) {
								innerhtmltext += (" checked='checked'")
							}
						}
						innerhtmltext += ('  onchange="onselectThisUser(this,\'' + apiurlList[j].url + '\')">' + apiurlList[j].url + '</input><br/>' + apiurlList[j].description + '</td></tr>');
					}
					apitablebody.innerHTML = innerhtmltext;
				}

				function onselectThisUser(selectUserItem, thisurl) {
					if(selectUserItem.checked == true) {
						addApiUserUrl(currentApiUserId, thisurl);
					} else {
						cutApiUserUrl(currentApiUserId, thisurl);
					}
				}
				var addapiUserlist = new Array()

				function addApiUserUrl(userid, thisurl) {
					var hasThisPrivilege = false;
					if(addapiUserlist) {
						allurllabel: for(key in apiUserUrlList) {
							for(var i = 0; i < apiUserUrlList[key].length; i++) {
								var useridOfurl = apiUserUrlList[key][i];
								if(useridOfurl == userid && key == thisurl) {
									hasThisPrivilege = true;
									break allurllabel;
								}
							}
						}
					}
					else {
						addapiUserlist = new Array();
					}
					if(hasThisPrivilege == false) {
						var newObject = new Object();
						newObject.user_token = userid;
						newObject.api_url = thisurl;
						newObject.enable = 1;
						newObject.id = 0;

						addapiUserlist = addapiUserlist.concat(newObject);
					} 
				}
				var removeApiUserUrlList = new Array();

				function cutApiUserUrl(userid, thisurl) {
					if(apiUserUrlList) {
						allurllabel: for(key in apiUserUrlList) {
							for(var i = 0; i < apiUserUrlList[key].length; i++) {
								var useridOfurl = apiUserUrlList[key][i];
								if(useridOfurl == userid) {
									var newObject = new Object();
									newObject.user_token = userid;
									newObject.api_url = thisurl;
									newObject.enable = 1;
									newObject.id = 0;
									removeApiUserUrlList = removeApiUserUrlList.concat(newObject);
									apiUserUrlList[key].splice(i, 1);
									break allurllabel;
								}
							}
						}
					} 
				}
				function clearAddFrom(){
				currentAppId = 0;	
				document.getElementById("user_name").value= "";
				document.getElementById("password").value= "";
				document.getElementById("apiEnable").checked = true;
				document.getElementById("description").value= ""; 
				}

				function saveApiUserUrl() {
					var sendObj = new Object()
					sendObj.add_api_user_urllist = addapiUserlist;
					sendObj.cutApi_user_urllist = removeApiUserUrlList;
					$.post(host + "/api_user_url/user/" + currentApiUserId, JSON.stringify(sendObj), saveApiUserUrlSuccess, "json");
				}

				function saveApiUserUrlSuccess(response, status, xhr) {
					if(status == "success" && response.reusltCode == "200") {
						apiUserUrlList = response.reusltDetail;
						removeApiUserUrlList = new Array();
						addapiUserlist = new Array();
						$('#setUserAPIModal').modal('hide');
						alert("保存成功");
					} else {
						alert(response);
					}

				}
			</script>
</body>